﻿using System;
using System.Drawing;
using System.Runtime.InteropServices;
using System.Windows.Forms;

namespace SerbinAV.Components
{
    public partial class NonFullScreenForm : Form
    {
        private bool centered = true;

        #region Native Platform Invoke

        [DllImport("coredll.dll")]
        private static extern UInt32 SetWindowLong(IntPtr hWnd, int nIndex, UInt32 dwNewLong);

        [DllImport("aygshell.dll")]
        private static extern int SHDoneButton(IntPtr hwndRequester, UInt32 dwState);

        private readonly int GWL_STYLE = (-16);

        private readonly UInt32 WS_CAPTION = 0x00C00000;     /* WS_BORDER | WS_DLGFRAME  */
        private readonly UInt32 WS_BORDER = 0x00800000;
        private readonly UInt32 WS_POPUP = 0x80000000;

        private readonly UInt32 SHDB_SHOW = 0x0001;
        private readonly UInt32 SHDB_HIDE = 0x0002;

        #endregion

        public bool CenterFormOnScreen
        {
            get
            {
                return centered;
            }
            set
            {
                centered = value;

                if (centered)
                {
                    CenterWithinScreen();
                }
            }
        }

        protected override void OnLoad(EventArgs e)
        {
            this.Height += SystemInformation.MenuHeight;
            base.OnLoad(e);
            uint style = WS_BORDER | WS_CAPTION | WS_POPUP;
            SetWindowLong(Handle, GWL_STYLE, style);
            SHDoneButton(Handle, ControlBox ? SHDB_SHOW : SHDB_HIDE);
            if (centered)
            {
                CenterWithinScreen();
            }
        }

        protected override void OnResize(EventArgs e)
        {
            base.OnResize(e);
            if (centered)
            {
                CenterWithinScreen();
            }
        }

        private void CenterWithinScreen()
        {
            int x = (Screen.PrimaryScreen.WorkingArea.Width - this.Width) / 2;
            int y = (Screen.PrimaryScreen.WorkingArea.Height - this.Height) / 2;

            this.Location = new Point(x, y);
        }
    }
}
